/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 * Description: remote rdma rma buffer interface
 */

#include "remote_rdma_rma_buffer.h"
#include "remote_rdma_rma_buffer_impl.h"

namespace hccl {
RemoteRdmaRmaBuffer::RemoteRdmaRmaBuffer()
    : RmaBuffer(nullptr, 0, HcclMemType::HCCL_MEM_TYPE_NUM, RmaType::RDMA_RMA)
{
    pimpl_ = std::make_unique<RemoteRdmaRmaBufferImpl>();
}

RemoteRdmaRmaBuffer::~RemoteRdmaRmaBuffer()
{
    if (pimpl_ != nullptr) {
        pimpl_  = nullptr;
        addr    = nullptr;
        size    = 0;
        devAddr = nullptr;
    }
}

HcclResult RemoteRdmaRmaBuffer::Deserialize(const std::string& msg)
{
    std::istringstream iss(msg);
    iss.read(reinterpret_cast<char_t *>(&addr), sizeof(addr));
    iss.read(reinterpret_cast<char_t *>(&size), sizeof(size));
    iss.read(reinterpret_cast<char_t *>(&devAddr), sizeof(devAddr));
    iss.read(reinterpret_cast<char_t *>(&memType), sizeof(memType));
    CHK_PTR_NULL(addr);
    CHK_PTR_NULL(devAddr);
    CHK_PRT_RET((memType >= HcclMemType::HCCL_MEM_TYPE_NUM),
        HCCL_ERROR("[RemoteRdmaRmaBuffer][Deserialize]HcclMemType[%d] is invalid.", memType), HCCL_E_PARA);
    CHK_PRT_RET((size == 0 || (memType == HcclMemType::HCCL_MEM_TYPE_HOST && size >= HOST_MEM_MAX_COUNT) ||
        (memType == HcclMemType::HCCL_MEM_TYPE_DEVICE && size >= DEVICE_MEM_MAX_COUNT)),
        HCCL_ERROR(
            "[RemoteRdmaRmaBuffer][Deserialize]memory size[%llu] should be greater than 0 and less than [%llu].",
            size,
            (memType == HcclMemType::HCCL_MEM_TYPE_DEVICE ? DEVICE_MEM_MAX_COUNT : HOST_MEM_MAX_COUNT)), HCCL_E_PARA);

    HCCL_DEBUG("[RemoteRdmaRmaBuffer][Deserialize]addr[%p], size[%llu], devAddr[%p], memType[%d]", addr, size, devAddr, memType);

    CHK_SMART_PTR_NULL(pimpl_);
    std::string remainingMsg = std::string((std::istreambuf_iterator<char>(iss)), std::istreambuf_iterator<char>());
    HcclResult ret = pimpl_->Deserialize(remainingMsg);
    if (ret != HCCL_SUCCESS) {
        pimpl_ = nullptr;
        HCCL_ERROR("[RemoteRdmaRmaBuffer]Deserialize failed, ret[%d]", ret);
        return ret;
    }
    return HCCL_SUCCESS;
}

u32 RemoteRdmaRmaBuffer::GetKey() const
{
    return pimpl_->GetKey();
}
}